class User < ActiveRecord::Base
  # Max & min lengths for all fields
  SCREEN_NAME_MIN_LENGTH = 4
  SCREEN_NAME_MAX_LENGTH = 20
  PASSWORD_MIN_LENGTH = 4
  PASSWORD_MAX_LENGTH = 40
  EMAIL_MAX_LENGTH = 50
  SCREEN_NAME_RANGE = SCREEN_NAME_MIN_LENGTH .. SCREEN_NAME_MAX_LENGTH
  PASSWORD_RANGE = PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH

  SCREEN_NAME_SIZE = 20
  PASSWORD_SIZE = 10
  EMAIL_SIZE = 30
  
  validates_uniqueness_of :screen_name, :email
  validates_length_of     :screen_name, :within => SCREEN_NAME_RANGE
  validates_format_of     :screen_name,
                             :with => /^[A-Z0-9_]*$/i,
                             :message => "只能包含字母，数字和下划线"
  validates_length_of     :password, :within => PASSWORD_RANGE
  validates_length_of     :email, :maximum => 50
  validates_format_of     :email,
                             :with => /^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i,
                             :message => "必须是合法的邮件地址"
  validates_presence_of   :email

  def validate
    errors.add(:email, "必须采用合法的形式") unless email.include?("@")
    errors.add(:screen_name, "不能包含空格") if screen_name.include?(" ")
  end

  def login!(session)
    session[:user_id] = id
  end

  def self.logout!(session)
    session[:user_id] = nil
  end

  #清楚密码
  def clear_password!
    self.password = nil
  end
end
